package danny.hoi.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import danny.hoi.domain.export.cargo.ContractProduct;
import danny.hoi.domain.export.cargo.ContractProductExample;
import danny.hoi.domain.export.cargo.Factory;
import danny.hoi.domain.export.cargo.FactoryExample;
import danny.hoi.service.cargo.ContractProductService;
import danny.hoi.service.cargo.FactoryService;
import danny.hoi.service.export.system.DeptService;
import danny.hoi.web.controller.base.BaseController;
import danny.hoi.web.utils.FileUploadUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {
    @Reference
    private FactoryService factoryService;
    @Reference(timeout = 100000)
    private ContractProductService contractProductService;
    @Autowired
    private DeptService deptService;


    /**
     * 1.分页显示
     * 2.请求地址：/cargo/contractProduct/list.do
     * 3.响应地址：
     */
    @RequestMapping("/list")
    public String list(String contractId,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        //查询所有的工厂
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        factoryExampleCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //查出当前购销合同下所有的货物
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria contractProductExampleCriteria = contractProductExample.createCriteria();
        contractProductExampleCriteria.andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo =
                contractProductService.findByPages(contractProductExample, pageNum, pageSize);

        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("factoryList", factoryList);
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-list";
    }

    /**
     * 1.保存数据
     * 2.请求地址：/cargo/contractProduct/edit.do
     * 3.响应地址：redirect:/cargo/contractProduct/list.do?contractId=
     */
    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());
        //文件上传
        if (productPhoto != null && !StringUtils.isEmpty(productPhoto.getOriginalFilename())) {
            String imgSrc = "";
            try {
                imgSrc = "http://" + fileUploadUtil.upload(productPhoto);
                contractProduct.setProductImage(imgSrc);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isEmpty(contractProduct.getId())) {
            //添加
            contractProductService.save(contractProduct);
        } else {
            //修改
            if (contractProduct.getProductImage() != null) {
                ContractProduct dbCp =
                        contractProductService.findById(contractProduct.getId());
                if (dbCp.getProductImage() != null) {
                    String key = dbCp.getProductImage().replaceAll("http://pw7yf5ava.bkt.clouddn.com/", "");
                    fileUploadUtil.delete(key);
                }
            }
            contractProductService.update(contractProduct);
        }

        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();
    }

    /**
     * 1.前往修改页面
     * 2.请求地址：/cargo/contractProduct/toUpdate.do?id=${o.id}
     * 3.响应地址：WEB-INF/pages/cargo/product/product-update.jsp
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);

        //查询所有的工厂
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        factoryExampleCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);
        return "cargo/product/product-update";
    }

    /**
     * 1.删除
     * 2.请求地址：cargo/contractProduct/delete.do?id=${o.id}&contractId=${o.contractId}
     * 3.响应地址：redirect:/cargo/contractProduct/list.do?contractId=
     */
    @RequestMapping("/delete")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }


    /**
     * 上传货物页面
     * 1.请求地址：http://localhost:8081/cargo/contractProduct/toImport.do?contractId=
     * 2.响应地址：WEB-INF/pages/cargo/product/product-import.jsp
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId) {
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-import";
    }

    /**
     * 1.上传
     * 2.请求地址：/cargo/contractProduct/import.do
     * 3.响应地址：
     */
    @RequestMapping("/import")
    public String importProduct(MultipartFile file, String contractId) {
        if (file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
            return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
        }
        try {
            //1.创建工作簿
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            //2.获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //3.获取总行数
            int rows = sheet.getPhysicalNumberOfRows();
            //获取企业id和名字
            String id = getLoginCompanyId();
            String name = getLoginCompanyName();
            for (int i = 0; i < rows; i++) {
                //4.获取第一行
                Row row = sheet.getRow(i + 1);
                //5.封装ContractProduct
                ContractProduct contractProduct = new ContractProduct();
                //6.企业id，企业名字，购销合同id
                contractProduct.setCompanyId(id);
                contractProduct.setCompanyName(name);
                contractProduct.setContractId(contractId);
                //7.封装excel表格数据
                contractProduct.setFactoryName(row.getCell(1).getStringCellValue());
                contractProduct.setProductNo(row.getCell(2).getStringCellValue());
                contractProduct.setCnumber((long) row.getCell(3).getNumericCellValue());
                contractProduct.setPackingUnit(row.getCell(4).getStringCellValue());
                contractProduct.setLoadingRate(String.valueOf(row.getCell(5).getNumericCellValue()));
                contractProduct.setBoxNum((long) row.getCell(6).getNumericCellValue());
                contractProduct.setPrice(row.getCell(7).getNumericCellValue());
                contractProduct.setProductDesc(row.getCell(8).getStringCellValue());
                contractProduct.setProductRequest(row.getCell(9).getStringCellValue());

                //8.存入数据库
                contractProductService.save(contractProduct);
            }

            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    /**
     * 1.模板下载
     * 2.请求地址：/cargo/contractProduct/downLoadModel.do
     * 3.响应地址：
     */
    @RequestMapping("/downLoadModel")
    public void downLoadModel(String contractId) {
        //获取模板输入流
        String model =
                session.getServletContext().getRealPath("/make/xlsprint/upload.xlsx");
        File file = new File(model);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=upload.xlsx");
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
